# -*- coding: utf-8 -*-
import os

activate_this = os.environ['VITTUAL_ENV_PATH']
execfile(activate_this, dict(__file__=activate_this))

import MySQLdb
import datetime,time,calendar
import logging

log_file_name = 'update_pw_to_hash.txt'

logging.basicConfig(filename = os.path.join(os.getcwd(), log_file_name), \
    level = logging.INFO, filemode = 'a', \
    format = '%(asctime)s - %(levelname)s: %(message)s')

import sys
sys.path.append("..")

from app.utilities import DateAndTimeHandler, SmsHandler, NjuUtility
from config_user import DISTRICT_GULOU,DISTRICT_XIANLIN

### STU
ID_NUM = 0
PW_NUM = 4
###

### TCH
#ID_NUM = 0
#PW_NUM = 4
###


def update_pw_to_hash():
    conn = MySQLdb.connect(host='localhost',port = 3306, \
       user='root', passwd='123456',db ='njusubsdb')

    logging.info("begin update:\n")
       
    cur = conn.cursor()
    cur_time = datetime.datetime.now()
    logging.info("alter_time:"+str(cur_time))

    hrs = cur.execute("select * from tch")

    hisrecs = cur.fetchmany(hrs)
    for elem in hisrecs:
        cur_id = str(elem[ID_NUM])
        cur_pw = elem[PW_NUM]
        if cur_pw is None or cur_pw=="":
            continue
        md5pw = NjuUtility.md5Encode(cur_pw)
        exe_st = "update tch set password='"+md5pw+"' where id="+cur_id
        
        logging.info(exe_st)
        logging.info(cur_id+"-"+cur_pw+"-"+md5pw+"\n")

        #ss = cur.execute(exe_st)

    cur.close()
    conn.commit()
    conn.close()

print("begin")
    
if __name__ == '__main__':
    print("begin")
    try:
        while True:
            update_pw_to_hash()
            #time.sleep(DateAndTimeHandler().sleep_time(1,0,0))
            break
    except Exception as e:
        logging.error(str(e))
        pass
        
